using Basket.Api.Domain;
using Microsoft.EntityFrameworkCore;

namespace Basket.Api.Data;

public class BasketDbContext(DbContextOptions<BasketDbContext> options) : DbContext(options)
{
    public DbSet<ShoppingBasket> Baskets => Set<ShoppingBasket>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<ShoppingBasket>(builder =>
        {
            builder.ToTable("baskets");
            builder.HasKey(b => b.Id);

            builder.Property(b => b.Id)
                .HasColumnName("id");

            builder.Property(b => b.UserId)
                .HasColumnName("user_id")
                .HasColumnType("uuid")
                .IsRequired();

            builder.HasIndex(b => b.UserId)
                .IsUnique();

            builder.Property(b => b.CreatedAt)
                .HasColumnName("created_at")
                .IsRequired();

            builder.Property(b => b.UpdatedAt)
                .HasColumnName("updated_at")
                .IsRequired();

            builder.OwnsMany(b => b.Items, items =>
            {
                items.ToTable("basket_items");
                items.WithOwner()
                    .HasForeignKey("basket_id");

                items.Property<Guid>("Id")
                    .HasColumnName("id")
                    .ValueGeneratedOnAdd();

                items.HasKey("Id");

                items.Property(i => i.ProductId)
                    .HasColumnName("product_id")
                    .IsRequired();

                items.Property(i => i.ProductName)
                    .HasColumnName("product_name")
                    .HasMaxLength(256)
                    .IsRequired();

                items.Property(i => i.UnitPrice)
                    .HasColumnName("unit_price")
                    .HasColumnType("numeric(18,2)")
                    .IsRequired();

                items.Property(i => i.Quantity)
                    .HasColumnName("quantity")
                    .IsRequired();
            });
        });
    }
}
